<!DOCTYPE html>
<html style="height: 100%">

<head>
    <meta charset="utf-8">
</head>

<body style="height: 100%; margin: 0">
    <button id="back">返回上一层</button>
    <div id="container" style="height: 100%"></div>
    <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts/echarts.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/superagent/4.0.0-alpha.1/superagent.min.js"></script>
    <script src="https://cdn.bootcss.com/co/4.1.0/index.min.js"></script>
    <script src="https://cdn.bootcss.com/lodash.js/4.17.10/lodash.min.js"></script>

    <script type="text/javascript">
        var dom = document.getElementById("container");
        var mapChart = echarts.init(dom);
        let option = null;
        const request = superagent;
        const click = [];
        /**
         * 生成option
         * @params {string} title 地图标题
         * @params {array} data 地图数据
         * @params {string} map 注册的地图名称
         */
        const genOption = (title, data, map = 'world') => {
            return {
                title: {
                    text: title,
                    left: 'center',
                },
                tooltip: {
                    trigger: 'item',
                    showDelay: 0,
                    transitionDuration: 0.2,
                    formatter: function (params) {
                        return `<p> place: ${params.name} </p><p>species: ${Number(params.value || 0).toFixed(0)} </p>`;
                    }
                },
                visualMap: {
                    left: 'right',
                    min: 0,
                    max: 10000,
                    inRange: {
                        color: ['rgb(255, 255, 255)', 'rgb(0, 250, 0)']
                    },
                    text: ['High', 'Low'],           // 文本，默认为数值文本
                    calculable: true
                },
                series: [
                    {
                        name: 'World物种分布',
                        type: 'map',
                        roam: true,
                        map: map,
                        itemStyle: {
                            emphasis: { label: { show: true } }
                        },
                        data: data
                    }
                ],                
            };
        }
        
        /**
         * 生成这个地区下的随机数据
         */
        const randomData = (place) => {
            const data = [];
            const children = place.children;
            for(let child of children){
                data.push(
                    { name: child.name, value: 10000 * Math.random(), id: child.id, group: child.group, },
                )
            }
            return data;
        }

        co(function *(){
            mapChart.showLoading();
            const geoWorld = yield superagent.get('./world.geo.json').then(d => d.text).then(JSON.parse);
            const worldJson = yield superagent.get('./world.json').then(d => d.text).then(JSON.parse);
            // ======> 随机生成一些数据
            const worldData = randomData(worldJson);
            // ======

            mapChart.hideLoading();
            let title = 'world';
            echarts.registerMap('world', geoWorld);

            option = genOption('world范围分布', worldData);
            mapChart.setOption(option, true);
            
            // 更新数据
            const updateMap = (name) => {
                if(name === 'world'){
                    const _option = genOption(`world物种范围分布`, randomData(worldJson), name);
                    mapChart.setOption(_option, true);
                    return ;
                }
                const find  = (click, data) => {
                    const _click = _.cloneDeep(click);
                    if(click.length === 0){
                        return data;
                    }
                    const name = _click.shift();
                    return find(_click, data.children.find(item => item.name === name));
                }
                const country = find(click, worldJson);
                if(country && country.file){
                    co(function * (){
                        const mapJson = yield superagent.get('geo/' + country.file).then(d => d.text).then(JSON.parse);
                        echarts.registerMap(name, mapJson);
                        const _option = genOption(`${name}物种范围分布`, randomData(country), name);
                        mapChart.setOption(_option, true);
                    });
                }else{
                    alert('没有下层数据');
                    // TODO: 重新处理这里的逻辑
                    click.pop();
                }
            }

            // 监听点击事件，下钻
            mapChart.on('click', function(data){
                const { name } = data;
                click.push(name);
                updateMap(name);
            })
            
            // 监听点击事件，返回
            $('#back').click(e => {
                if(click.length === 0){
                    alert('顶层数据');
                    return;
                }
                const name = click.pop();
                if(click.length === 0){
                    updateMap('world');
                }
                const _click = _.cloneDeep(click);
                updateMap(_click.pop());
            });
        });
    </script>
</body>

</html>